package com.tony.pmp.server.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.tony.pmp.common.utils.Constant;
import com.tony.pmp.model.entity.SysMenuEntity;
import com.tony.pmp.model.entity.SysUserEntity;
import com.tony.pmp.model.mapper.SysUserMapper;
import com.tony.pmp.server.service.SysMenuService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: UserRealm
 * @Auther: 皮蛋布丁
 * @Date: 2021/07/11/16:23
 * @Description: 自定义Realm
 */
@Component
public class UserRealm extends AuthorizingRealm {

    private static final Logger log= LoggerFactory.getLogger(UserRealm.class);

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysMenuService sysMenuService;

    /**
    * @Description: doGetAuthorizationInfo 资源权限分配的授权-核心1(需要将分配给当前用户的权限列表塞给shiro的权限字段中去)
    * @Param: [principalCollection]
    * @return: org.apache.shiro.authz.AuthorizationInfo
    * @Author: 皮蛋布丁
    * @Date: 2021/7/11 16:35
    */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前登录用户(主体)
        SysUserEntity user = (SysUserEntity) principalCollection.getPrimaryPrincipal();
        Long userId = user.getUserId();
        List<String> perms = Lists.newLinkedList();

        //超级管理员拥有全部权限；否则根据用户id查询权限列表
        if (userId == Constant.SUPER_ADMIN) {
            List<SysMenuEntity> list = sysMenuService.list();
            if (list != null && !list.isEmpty()) {
                perms = list.stream().map(SysMenuEntity::getPerms).collect(Collectors.toList());
            }
        } else {
            perms = sysUserMapper.queryAllperms(userId);
        }
        //对于每一个授权编码进行 , 的解析拆分
        Set<String> stringPermissions= Sets.newHashSet();
        if (perms!=null && !perms.isEmpty()){
            for (String p:perms){
                if (StringUtils.isNotBlank(p)){
                    stringPermissions.addAll(Arrays.asList(StringUtils.split(p.trim(),",")));
                }
            }
        }

        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setStringPermissions(stringPermissions);
        return info;
    }

    /**
    * @Description: doGetAuthenticationInfo 用户认证(登录认证)-核心2
    * @Param: [authenticationToken]
    * @return: org.apache.shiro.authc.AuthenticationInfo
    * @Author: 皮蛋布丁
    * @Date: 2021/7/11 16:35
    */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken;
        final String userName=token.getUsername();
        final String password=String.valueOf(token.getPassword());

        log.info("用户名: {} 密码：{}",userName,password);

        SysUserEntity entity=sysUserMapper.selectOne(new QueryWrapper<SysUserEntity>().eq("username",userName));
        //账户不存在
        if (entity==null){
            throw new UnknownAccountException("账户不存在!");
        }
        //账户被禁用
        if (0 == entity.getStatus()){
            throw new DisabledAccountException("账户已被禁用,请联系管理员!");
        }

        //region 第一种: 明文匹配
        //账户名密码不匹配
//        if (!entity.getPassword().equals(password)){
//            throw new IncorrectCredentialsException("账户密码不匹配!");
//        }
//        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(entity,password,getName());
//        return info;
        //endregion

        //region 第二种：交给shiro的密钥匹配器去实现
//        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(entity, entity.getPassword(), ByteSource.Util.bytes(entity.getSalt()), getName());
//        return info;
        //endregion

        //region 第三种：前端传递的明文+数据库的盐加密后匹配(比较常用)
        String realPassword=ShiroUtil.sha256(password,entity.getSalt());
        if (StringUtils.isBlank(realPassword) || !realPassword.equals(entity.getPassword())){
            throw new IncorrectCredentialsException("账户密码不匹配!");
        }
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(entity,password,getName());
        return info;
        //endregion
    }

    /**
    * @Description: setCredentialsMatcher 第二种：shiro自带密码验证器
    * @Param: [credentialsMatcher]
    * @return: void
    * @Author: 皮蛋布丁
    * @Date: 2021/7/11 21:09
    */
//    @Override
//    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
//        HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();
//        shaCredentialsMatcher.setHashAlgorithmName(ShiroUtil.hashAlgorithmName);
//        shaCredentialsMatcher.setHashIterations(ShiroUtil.hashIterations);
//        super.setCredentialsMatcher(shaCredentialsMatcher);
//    }
}
